<template>
  <div class="app-container" id="user">
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="用户编码:">
        <el-input v-model="queryForm.usercode" placeholder="请输入用户编码" clearable />
      </el-form-item>
      <el-form-item label="用户名称:">
        <el-input v-model="queryForm.username" placeholder="请输入用户名称" clearable />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryForm.indatetime"
          type="date"
          placeholder="创建时间"
          clearable
        />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="fetchTableData">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" style="margin-bottom: 10px;">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            size="small"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
    
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>    
        
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Upload"
            size="small"
            @click="handleAllin"
          >导入</el-button>
        </el-col>
      </el-row>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%;" :header-cell-style="{ backgroundColor: '#F8F8F8' }" :height="tableHeight"
     border  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="55" align="center">
        <template v-slot="scope">
          {{ (queryForm.pageNum - 1) * queryForm.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column property="usercode" label="用户编码" align="center"/>
      <el-table-column property="username" label="用户名称" show-overflow-tooltip min-width = "200" align="center"/>
      <el-table-column property="rolecode" label="分配角色" show-overflow-tooltip align="center">
        <template #default="scope">
            <!-- 使用 computed 方法处理 menulist 显示的内容 -->
          <span>{{ getRoleName(scope.row.rolecode) }}</span>
        </template>
      </el-table-column>
      <el-table-column property="suplist" label="分配供应商" show-overflow-tooltip min-width = "200" align="center">
        <template #default="scope">
          <span>{{ getSupName(scope.row.suplist) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <span>{{ scope.row.status === '1' ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="bgndate" label="生效日期" align="center">
        <template #default="scope">
           <span>{{ scope.row.bgndate && scope.row.bgndate.split(' ')[0] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enddate" label="到期日期" align="center">
        <template #default="scope">
          <span>{{ scope.row.enddate && scope.row.enddate.split(' ')[0] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" show-overflow-tooltip align="center">
        <template #default="scope">{{ scope.row.indatetime }}</template>
      </el-table-column>
      <el-table-column label="操作" width="330" align="center">
        <template #default="scope">
            <el-button type="primary" @click="handleDelete(scope.row)">
              <el-icon style="vertical-align: middle">
               <Delete />
              </el-icon>
              <span style="vertical-align: middle"> 删 除 </span>
            </el-button>
            <el-button type="primary" @click="handleEdit(scope.row)">
              <el-icon style="vertical-align: middle">
              <Edit />
              </el-icon>
              <span style="vertical-align: middle"> 修 改 </span>
            </el-button>
            <el-button type="primary" @click="handleRenSetPassword(scope.row)">
              <el-icon style="vertical-align: middle">
              <Compass />
              </el-icon>
              <span style="vertical-align: middle"> 重置密码 </span>
            </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:20px; display:flex; align-items:center; justify-content:right;">
      <el-select v-model="queryForm.pageSize" @change="handlePageSizeChange" style="width: 100px; margin-right: 10px">
        <el-option label="10条/页" :value="10" />
        <el-option label="20条/页" :value="20" />
        <el-option label="50条/页" :value="50" />
        <el-option label="100条/页" :value="100" />
      </el-select>
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page-size="queryForm.pageSize"
        :current-page="queryForm.pageNum"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePagination"
      />
    </div>

    <!-- 新增、编辑框 -->
    <el-dialog :title="data.title" v-model="data.open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form  ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户编码" prop="usercode">
          <el-input v-model="form.usercode" />
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="选择角色" prop="rolecode">
          <el-select
            v-model="form.rolecode"
            placeholder="请选择角色"
            :filterable="false"
            clearable
          >
            <el-option
              v-for="role in data.roles"
              :key="role.rolecode"
              :label="role.rolename"
              :value="role.rolecode"
            />
          </el-select>
        </el-form-item> 
        <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="'0'">禁用</el-radio>
          <el-radio :value="'1'">启用</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="供应商选择" prop="menulist">
          <div class="sup-selector">
            <!-- 搜索框 -->
            <el-input
              v-model="supSearchText"
              placeholder="输入供应商编码或名称搜索"
              clearable
              @clear="handleSearchClear"
              @input="handleSupSearch"
              class="sup-search"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <!-- 全选/不选 -->
            <div class="check-all">
              <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选/全不选</el-checkbox>
              <span class="checked-count">已选 {{ form.suplist.length }} 项</span>
            </div>
            
            <!-- 复选框组 -->
            <el-checkbox-group 
              v-model="form.suplist" 
              class="checkbox-group"
            >
              <el-checkbox 
                v-for="sup in filteredRoles" 
                :key="sup.supcode" 
                :value="sup.supcode"
                class="sup-checkbox"
              >
                <span class="sup-name">{{ sup.supcode }} - {{ sup.supname }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref,computed , onMounted, nextTick } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { getMenuList, getUserMenuList} from '@/api/system/menu.js'
import { getAllSups } from '@/api/system/supplier.js'
import { getUserList, addUser,delUser,editUser ,getRoleList ,batchAdd} from '@/api/system/user.js'
import { ElMessageBox, ElMessage ,ElLoading  } from 'element-plus';

const queryForm = reactive({
  usercode:'',
  username: '',
  indatetime: '',
  pageNum: 1,
  pageSize: 10
})

// 创建响应式数据
const ids = ref([]) // 多选框选中的 id
const single = ref(false) // 是否为单选
const multiple = ref(true) // 是否为多选
const formRef = ref(null);
const checkAll = ref(false)

// 搜索相关状态
const supSearchText = ref('')

// 计算属性：过滤后的角色列表
const filteredRoles = computed(() => {
  if (!supSearchText.value) return supLists.value
  
  const searchText = supSearchText.value.toLowerCase()
  return supLists.value.filter(sup => 
    sup.supcode.toLowerCase().includes(searchText) || 
    sup.supname.toLowerCase().includes(searchText)
  )
})

// 搜索处理函数
const handleSupSearch = () => {
  checkAll.value = false // 搜索时自动取消全选状态
}

// 清空搜索
const handleSearchClear = () => {
  supSearchText.value = ''
}
// 处理选择变更的函数
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.usercode)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}
const supLists = ref([])
// 定义表单数据
const form = reactive({
  rolecode:'',
  usercode:'',
  username: '',
  status: '1',
  suplist: [], // 存储选中的角色supcode
  remark: ''
})

// 定义校验规则
const rules = reactive({
  usercode: [
    { required: true, message: '用户编码不能为空', trigger: 'blur' },
  ],
  rolecode: [
    { required: true, message: '角色不能为空', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '状态必选项', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' }
  ]
})

const data = reactive({
  doType: '',
  open: false,
  title: '',
  roles:[], //系统中已创建的角色
  permissionOptions: [],
  menuNodeAll: false // 添加 menuNodeAll
})

const total = ref(0)
const open = ref(false)
const tableData = ref([])

const tableHeight = ref("585px")

const fetchTableData = async () => {
  try {
    // 获取用户列表
    const res = await getUserList(queryForm);  
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取用户列表失败:', error);  
  }
}

// 在组件挂载后获取数据
onMounted(() => {
  getAllMenuList().then(() => {
    fetchTableData()
    fetchRoleList()
    fetchAllSups()
  })
  // tableHeight.value = window.innerHeight - 250 + "px"; // 计算表格高度
})

//批量导入用户
const handleAllin = async () => {
  let loadingInstance;

  try {
    // 等待用户点击“确定”或“取消”
    await ElMessageBox.confirm('是否确认导入所有供应商？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 用户点击了“确定”，执行后续操作
    loadingInstance = ElLoading.service({
      lock: true,  // 锁定页面
      text: '正在导入数据，请稍候...', // 提示文字
      spinner: 'el-icon-loading', // 加载图标
      background: 'rgba(0, 0, 0, 0.7)', // 背景颜色
    });

    // 执行批量添加操作
    const res = await batchAdd(supLists.value);

    // 完成后关闭加载指示器
    loadingInstance.close();

    // 根据返回结果显示导入成功提示
    if (res.code === 200) {
      const rows = res.rows ? Number(res.rows) : 0;
      ElMessage.success(`导入成功 ${rows} 条`);
    }
    fetchTableData()

  } catch (error) {
    // 完成后关闭加载指示器
    if (loadingInstance) {
      loadingInstance.close();
    }

    // 如果是用户取消操作，不显示错误提示
    if (error !== 'cancel') {
      ElMessage.error("导入失败" + error);
    }
  }
};


//加载所有供应商
const fetchAllSups = async () => {
  const res = await getAllSups()
  if(res.code){
    supLists.value = res.data
  }
}

//加载已创建的角色列表
const fetchRoleList = async () => {
  const res = await getRoleList()
  if (res.code === 200) data.roles = res.rows
}

//通过rolecode匹配rolename
const getRoleName = (rolecode) => {
  if (!rolecode || !data.roles) return ''
  const role = data.roles.find(item => item.rolecode == rolecode)
  return role ? role.rolename : ''
}
 
 //通过supcode匹配supname
const getSupName = (supcode) => {
  if (!supcode || !supLists.value) return '';
  // 1. 统一转字符串，并拆分逗号分隔的 supcode
  const supcodeArray = String(supcode).split(',');
  // 2. 在 supLists.value 中查找匹配的供应商（统一转字符串比较）
  const matchedSups = supLists.value.filter(item => 
    supcodeArray.includes(String(item.supcode))
  );
  // 3. 提取供应商名称并用逗号拼接
  return matchedSups.map(item => item.supname).join(',');
};
 
//打开新增窗口
const handleAdd = async () => {
  data.open = true
  data.title = "新增"
  data.doType = "add"
  form.usercode = ''
  form.username = ''
  form.rolecode = ''
  form.status = '1'
  form.suplist = []
  form.remark = ''
}

// 打开编辑窗口
const handleEdit = async (row) => {
  // 检查 checkbox 是否有数据
    if (!supLists.value ||supLists.value.length === 0) {
      getAllSups()
    }
    await nextTick()
    // 1. 先处理 row.suplist（转为数组）
    const processedRow = {
      ...row,
      suplist: typeof row.suplist === 'string' ? row.suplist.split(',') : row.suplist
    };
    // 2. 再拷贝到 form
   Object.assign(form, processedRow);
   data.doType = "edit"
   data.title = "用户编辑"
   data.open = true 
}

const handleDelete = async (row) => {
  try {
    const usercode = row.usercode || ids.value;
    await ElMessageBox.confirm('是否确认删除所选用户？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
  const res = await delUser(usercode);
  await fetchTableData();
   if(res.code == 200){
      ElMessage.success(res.rows); 
   };

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("删除失败" + error);
    }
  }
}

//处理新增和编辑逻辑
const onSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请正确填写表单");
      return;
    }
    const formData = {
      ...form, 
      suplist: [...form.suplist].join(',') 
    };
   
    if (data.doType === 'add') {
      const res = await addUser(formData);
      if (res.code !== 200) {
        ElMessage.error(res.msg || "新增失败");
        return;
      }
      ElMessage.success("新增成功");
      data.open = false;
      fetchTableData();
    } else if (data.doType === 'edit') {
      const res = await editUser(formData);
      if (res.code !== 200) {
        ElMessage.error(res.msg || "编辑失败");
        return;
      }
      ElMessage.success("编辑成功");
      data.open = false;
      fetchTableData();
    }
  });
};


const cancel = () => {
  data.open = false
}
const handlePagination = (pageNum) => {
  queryForm.pageNum = pageNum
  fetchTableData()
}

const handlePageSizeChange = () => {
  queryForm.pageNum = 1
  fetchTableData()
}

// 获取所有菜单项
const getAllMenuList = async () => {
  const res = await getMenuList()
  data.permissionOptions = res.rows
}

// 全选/全不选处理
const handleCheckAllChange = (val) => {
  form.suplist = val ? supLists.value.map(item => item.supcode) : []
}




</script>

<style>
.sup-selector {
  width: 90%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.sup-search {
  margin-bottom: 10px;
}

.check-all {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  margin-bottom: 5px;
  border-bottom: 1px dashed #eee;
}

.checked-count {
  font-size: 12px;
  color: #999;
}


.checkbox-group {
  display: flex;
  flex-direction: column;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 5px;
}

.sup-checkbox {
  margin-bottom: 8px;
  margin-right: 0;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sup-checkbox:hover {
  background-color: #f5f7fa;
}

.sup-code {
  display: inline-block;
  width: 80px;
  color: #666;
  font-family: monospace;
}

.sup-name {
  margin-left: 10px;
}

/* 滚动条样式 */
.checkbox-group::-webkit-scrollbar {
  width: 6px;
}

.checkbox-group::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.checkbox-group::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
  
.app-container {
  padding: 20px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 添加边框样式 */
.tree-border {
  width: 100%;
  border: 1px solid #dcdfe6;  /* 设置边框颜色 */
  border-radius: 4px;         /* 设置圆角 */
  padding: 10px;              /* 设置内边距（可选） */
}

/* 新增、编辑框按钮 */
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* tree菜单复选框 */
.el-checkbox:last-of-type {
    margin-right: 5px;
}

.el-table {
  user-select: text;
}

.el-table__body td {
  user-select: text;
}
</style>
